package com.hqq.exercise.array;

/**
 * PrintMatrixClockWisely 顺时针打印矩阵
 * 题目描述:
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字
 * 样例输入:
 * 1  2  3  4
 * 5  6  7  8
 * 9  10 11 12
 * 13 14 15 16
 * 样例输出:
 * 1 2 3 4 8 12 16 15 14 14 9 5 6 7 11 10
 * Created by heqianqian on 2017/8/13.
 */
public class PrintMatrixClockWisely {

    /**
     * 顺时针打印矩阵
     *
     * @param matrix 矩阵
     */
    public static void printMatrixClockWisely(int[][] matrix) {
        if (matrix == null) {
            return;//如果矩阵为空 就返回
        }
        int start = 0;//左上角坐标 [x==y]
        //行数和列数
        int rows = matrix.length, columns = matrix[0].length;
        while (rows > start * 2 && columns > start * 2) {//循环的条件
            printMaxInCircle(matrix, columns, rows, start);
            ++start;
        }
    }

    /**
     * 按圈打印矩阵
     */
    private static void printMaxInCircle(int[][] matrix, int columns, int rows, int start) {
        int endX = columns - 1 - start;
        int endY = rows - 1 - start;
        //从左往右打印
        for (int i = start; i <= endX; ++i) {
            int number = matrix[start][i];
            printNumber(number);
        }
        //从上往下打印一列
        if (start < endY) {
            for (int i = start + 1; i <= endY; ++i) {
                int number = matrix[i][endX];
                printNumber(number);
            }
        }
        //从右往左打印一行
        if (start < endX && start < endY) {
            for (int i = endX - 1; i >= start; --i) {
                int number = matrix[endY][i];
                printNumber(number);
            }
        }
        //从下到上打印一行
        if (start < endX && start < endY - 1) {
            for (int i = endY - 1; i >= start; --i) {
                int number = matrix[i][endX];
                printNumber(number);
            }
        }
    }

    private static void printNumber(int number) {
        System.out.print(number + " ");
    }
}
